<template>
    <div class="content">
            <van-form @submit="onSubmit" validate-first @failed="onFailed">
                <div v-show="formModel===true">
                    <div class="title">Basic Information</div>
                    <van-field
                            v-model="relationInfo.name"
                            name="name"
                            label="Name"
                            placeholder="Please fill in your real name."
                            :maxlength="20"
                    />
                    <van-field
                            v-model="relationInfo.relation"
                            name="relation"
                            label="Relation"
                            placeholder="Please fill in your agency relationship."
                    />
                    <van-field
                            readonly
                            v-model="relationInfo.cardno"
                            name="card_no"
                            label="Passport No"
                            @blur="bodyScrollTop"
                    />
                    <div class="div-bot">
                        <van-button round block type="info"
                                    native-type="submit"
                                    :disabled="disabled"
                                    class="city-card-common-btn">
                            Submit
                        </van-button>
                    </div>
                </div>
                <div v-show="formModel===false">
                    <div class="title">Basic Information</div>
                    <van-field
                            v-model="formItem.name"
                            name="name"
                            :readonly="updataState"
                            label="Name"
                            placeholder="Please fill in your real name."
                            :maxlength="20"
                    />
                    <van-field
                            :readonly="updataState"
                            v-model="formItem.card_no"
                            name="card_no"
                            label="Passport No"
                            @blur="bodyScrollTop"
                    />
                    <van-field v-model="formItem.tel"
                               name="tel" label="Cellphone No" :rules="phoneRules"/>

                    <area-page ref="areaPage" :formData="formItem"></area-page>

                    <div class="title">Recent Travel History</div>
                    <recent-situation ref="recentSituation" :formData="formItem"></recent-situation>

                    <div class="div-bot">
                        <van-button round block type="info"
                                    native-type="submit"
                                    :disabled="disabled"
                                    class="city-card-common-btn">
                            {{btnText}}
                        </van-button>
                    </div>
                </div>
            </van-form>

<!--        <van-tabbar>-->
<!--            <van-tabbar-item icon="chat-o" name='1' url="https://mp.weixin.qq.com/s/BQKXZgb3YHiy38csfv9cjQ">在线客服-->
<!--            </van-tabbar-item>-->
            <!--<van-tabbar-item icon="service-o" name='2' url="https://mp.weixin.qq.com/s/TRLYCrEDWHg0CYRPkeaSWw">视频客服
            </van-tabbar-item>-->
<!--        </van-tabbar>-->
    </div>
</template>

<script>
// 接口
import { userUpdatepermit, getByCardNo, getOpenidMsg, insertPermitPerson, insertPermitChildren } from '@/api/yi-qing-fang-kong.js'
// 工具
import { identityCodeValid, identityMobile } from '@/libs/tools'
// 组件
import { Dialog } from 'vant'
import AreaPage from './wai-ji-components/area-page/index'
import RecentSituation from './wai-ji-components/recent-situation/index'
// import wx from 'weixin-js-sdk'

export default {
  components: { RecentSituation, AreaPage },
  data () {
    this.phoneRules = [
      { required: true, message: 'Please type in the correct mobile phone number.' },
      { validator: this.phoneValidator, message: 'Wrong mobile phone number format.' }
    ]
    // this.codeRules = [
    //   { required: true, message: '请输入验证码' },
    //   { validator: this.codeValidator, message: '验证码错误' }
    // ]
    return {
      formModel: true,
      relationInfo: {
        name: '',
        cardno: '',
        relation: ''
      },
      formItem: {
        // 表单数据
        name: '',
        card_no: '',
        tel: '',
        area_type: '', // 区域类型
        area_id: '',
        street_id: '',
        community_id: '',
        area: '',
        street: '',
        community: '',
        loc_province: '', // 地图选取后的省
        loc_city: '', // 地图选取后的市
        loc_title: '', // 地图选取后的地址名
        loc_address: '', // 地图选取后的具体地址
        house_num: '', // 门牌号
        is_hubei: '',
        is_contact: '',
        health_state: '',
        temp: '',
        p1: ''
      },
      loading: false,
      updataState: true,
      loadingText: '加载中',
      btnText: '提交',
      disabled: false,
      mine_card_no: '',
      routeObj: {} // 路由对象
    }
  },
  methods: {
    getOpenidInfoAction () {
      getOpenidMsg().then(ret => {
        console.log('判断是否注册过', ret.data)
        if (ret.data.errcode === 0) {
          this.mine_card_no = ret.data.data.result.card_no
          // if (!this.$common.xeUtils.isEmpty(ret.data.data.result)) {
          // this.successModel = true
          // this.$router.push({
          //   name: 'epidemic-submit-success',
          //   query: {}
          // })
          // }
        } else {
          // this.failNotice(ret.data.errmsg)
        }
      })
    },
    failNotice (title) {
      this.$notify({ type: 'danger', message: title })
    },
    idCardValidator (val) {
      // 身份证
      const reg1 = identityCodeValid(val)
      if (!reg1.pass) {
        // this.failNotice('请检查身份证格式！')
        return false
      }
    },
    phoneValidator (val) {
      return identityMobile(val)
    },
    onFailed (errorInfo) {
      this.failNotice(errorInfo.errors[0].message)
      console.log('failed', errorInfo)
    },
    onSubmit (value) {
      console.log('表单提交', value)
      if (this.formModel === true) {
        if (this.$route.query.type === '0') {
          insertPermitChildren(this.relationInfo).then(ret => {
            if (ret.data.errcode === 0) {
              console.log('插入亲人成功', ret.data)
              this.$dialog.alert({
                message: 'Submitted successfully'
              }).then(() => {
                this.$router.push({
                  name: 'epidemic-submit-success-waiji',
                  query: {}
                })
              })
              /*   Toast.success('保存成功') */
            } else {
              this.$dialog.alert({
                message: ret.data.errmsg
              })
            }
          })
        }
        if (this.$route.query.type === '1') {
          insertPermitPerson(this.relationInfo).then(ret => {
            if (ret.data.errcode === 0) {
              console.log('插入亲人成功', ret.data)
              this.$dialog.alert({
                message: 'Submitted successfully'
              }).then(() => {
                this.$router.push({
                  name: 'epidemic-submit-success-waiji',
                  query: {}
                })
              })
              /*   Toast.success('保存成功') */
            } else {
              this.$dialog.alert({
                message: ret.data.errmsg
              })
            }
          })
        }
      } else {
        if (this.formItem.card_no === '' || this.formItem.card_no === undefined || this.formItem.card_no === null) {
          this.$dialog.alert({
            message: 'Please fill in the real passport number!'
          })
          return false
        }
        // 区域部分
        let areaPageData = this.$refs.areaPage.checkForm()
        // 姓名去空格处理
        this.formItem.name = this.formItem.name.toString().replace(/\s/ig, '')
        // 手机号去空格处理
        this.formItem.tel = this.formItem.tel.toString().trim()
        // 身份证去空格处理
        this.formItem.card_no = this.formItem.card_no.toString().trim()

        if (this.formItem.tel.length !== 11) {
          this.failNotice('Please type in the correct mobile phone number.')
          return false
        } else {
          console.log(this.formItem.tel, '手机位数为：' + this.formItem.tel.length)
        }

        console.log('区域组件', areaPageData)
        let recentSituationData = this.$refs.recentSituation.checkForm()
        console.log('其它信息组件', recentSituationData)
        if (areaPageData && recentSituationData) {
          // if (areaPageData) {
          // 组件数据处理
          this.formItem.area_type = areaPageData.area_type
          this.formItem.area_id = areaPageData.area.id
          this.formItem.area = areaPageData.area.text
          this.formItem.street_id = areaPageData.street.id
          this.formItem.street = areaPageData.street.text
          this.formItem.community_id = areaPageData.community.id
          this.formItem.company_code = !this.$common.xeUtils.isEmpty(areaPageData.community.company_code) ? areaPageData.community.company_code : areaPageData.street.company_code
          this.formItem.community = areaPageData.area_type === '1' ? areaPageData.community.text : areaPageData.cunValue
          this.formItem.house_num = areaPageData.house_num
          this.formItem.loc_title = areaPageData.title
          this.formItem.loc_address = areaPageData.address
          this.formItem.loc_province = areaPageData.province
          this.formItem.loc_city = areaPageData.city
          this.formItem.longitude = areaPageData.lng
          this.formItem.latitude = areaPageData.lat
          this.formItem.address = this.formItem.loc_province + this.formItem.loc_city + this.formItem.loc_title + this.formItem.loc_address
          this.formItem.is_hubei = recentSituationData.is_hubei
          this.formItem.is_contact = recentSituationData.is_contact
          this.formItem.health_state = recentSituationData.health_state_copy.join('^')
          this.formItem.health_state.replace(/,/g, '^')
          this.formItem.temp = recentSituationData.temp
          this.formItem.stay_city = recentSituationData.stay_city
          // 移除arrive_time防止sql报错
          this.$delete(this.formItem, 'arrive_time')
          // 校验成功后插入
          if (this.formItem.is_contact.toString() === '1') {
            Dialog.alert({
              title: 'WARM TIPS',
              message: '<span style="color:red;">Please reconfirm that novel coronavirus pneumonia confirmed case or suspected case in the past 14 days？</span>'
            }).then(() => {
              this.updatePermitAction()
            })
          } else {
            this.updatePermitAction()
          }
        }
      }
    },
    // 表单提交
    updatePermitAction () {
      this.formItem.id = this.$route.query.id
      if (this.$route.query.type === '0') {
        this.formItem.p1 = 'children'
      }
      if (this.$route.query.type === '1') {
        this.formItem.p1 = 'person'
      }
      // this.formItem.card_no2 = this.formItem.card_no
      // this.formItem.card_no = this.mine_card_no
      console.log('表单最终提交内容', this.formItem)
      // type不为2时姓名、身份证号、手机号移除
      let item = this.$common.xeUtils.clone(this.formItem)
      // if (this.updataState) {
      //   this.$delete(item, 'name')
      //   this.$delete(item, 'card_no')
      // }
      userUpdatepermit(item).then(ret => {
        if (ret.data.errcode === 0) {
          console.log('保存回调', ret.data.data)
          this.$dialog.alert({
            message: 'Saved successfully!'
          }).then(() => {
            this.$router.push({
              name: 'epidemic-submit-success-waiji',
              query: {}
            })
          })
        } else {
          this.failNotice(ret.data.errmsg + '/sid/' + ret.data.sid)
        }
      })
    },
    getOpenidMsgAction () {
      let data = {
        // card_no: this.$route.query.cardno,
        id: this.$route.query.id
      }
      if (this.$route.query.type === '0') {
        data.p1 = 'children'
      }
      if (this.$route.query.type === '1') {
        data.p1 = 'person'
      }
      getByCardNo(data).then(ret => {
        if (ret.data.errcode === 0) {
          console.log('获取注册过的人员信息', ret.data)
          let data = ret.data.data.result
          if (this.routeObj.type === '1') {
            if (data.name === ret.data.data.person.name) {
              console.log('父母代办，并且名字相同')
              this.formModel = false
            } else {
              console.log('父母代办，并且名字不相同')
              this.formModel = true
              this.relationInfo = ret.data.data.person
            }
          } else if (this.routeObj.type === '0') {
            if (data.name === ret.data.data.children.name) {
              console.log('儿童代办，并且名字相同')
              this.formModel = false
            } else {
              console.log('儿童代办，并且名字不相同')
              this.formModel = true
              this.relationInfo = ret.data.data.children
            }
          } else {
            this.formModel = true
          }
          if (!this.$common.xeUtils.isEmpty(data)) {
            this.formItem = data
            this.formItem.address = this.formItem.loc_address
            if (this.formItem.type === 3 || this.formItem.type === 8) {
              this.disabled = true
              this.btnText = 'Unable to submit'
            } else {
              this.disabled = false
              this.btnText = 'Submit'
            }
            this.updataState = this.formItem.type !== '2'
            this.autoDataHandle()
          }
        } else if (ret.data.errcode === 9998) {
          this.$dialog.alert({
            message: 'Saved successfully!'
          }).then(() => {
            this.$router.push({
              name: 'epidemic-submit-new-waiji',
              query: {}
            })
          })
        } else {
          this.failNotice(ret.data.errmsg)
        }
      })
    },
    // 去苹果机型白边
    bodyScrollTop () {
      winToTop()
    },
    // 回显数据处理
    autoDataHandle () {
      console.log('当前表单', this.formItem)
    }
  },
  mounted () {
    this.getOpenidInfoAction()
    // this.$dialog.alert({
    //   title: '温馨提示',
    //   message: '每人只可修改一次'
    // })
    // 获取路由信息
    this.routeObj = this.$route.query
    console.log('表单页面路由信息', this.routeObj)
    // 获取填报信息
    this.getOpenidMsgAction()
    console.log('表单信息', this.formItem)
  },
  computed: {},
  watch: {}
}
</script>

<style scoped>
    .address-box {
        text-align: left;
    }

    .van-radio {
        float: left;
        margin-right: 10px;
    }

    .van-popup /deep/ .van-ellipsis {
        font-size: 0.95rem;
    }

    .title {
        width: 100%;
        padding: 0.625rem 0.9375rem;
        font-size: 12px;
    }

    .action-item .van-cell__title {
        -webkit-box-flex: inherit;
        -webkit-flex: inherit;
        flex: inherit;
        width: 5.625rem;
    }

    .content {
        width: 100%;
        background-color: #F5F5F5;
        box-sizing: border-box;
        -webkit-box-sizing: border-box;
    }

    .content >>> .van-cell {
        margin: 0 2%;
        width: 96%;
        font-size: 12px;
    }

    .content >>> .van-dialog__content {
        padding: 10px;
        text-align: center;
    }

    .van-field__control {
        font-size: 12px;
    }

    .content >>> .van-cell__value .van-field__body .van-field__control {
        font-size: 12px;
    }

    .div-bot {
        margin: 10px;
        margin-bottom: 60px;
    }

    .div-bot >>> .van-button--info {
        border: 1px solid #75ACDC;
    }

    .div-bot >>> .van-button {
        height: 2.5rem;
    }

    .city-card-common-btn {
        color: white;
        font-size: 12px;
        padding: 0;
        width: 100%;
        border-radius: 5px;
        text-align: center;
        background-color: #75ACDC;
    }

    .content >>> .van-cell__value {
        /*flex: inherit;*/
        font-size: 12px;
    }

    .content >>> .van-cell__value {
        text-align: left;
    }

    .content >>> .value-item .van-cell__value {
        width: 100%;
    }

    .van-action-sheet__cancel, .van-action-sheet__item {
        font-size: 12px;
    }

    .van-cell__value span {
        /*color: black;*/
    }

    .van-dropdown-menu {
        height: 25px;
    }

    .van-hairline--top-bottom::after {
        border-width: 0px 0px;
    }

    .chaochu >>> .van-cell__value {
        width: 100%;
    }

    .div1 >>> .van-cell__value {
        width: 100%;
    }

    .div2 >>> .van-cell__value {
        width: 100%;
    }

    .other-info .van-field__label.radio-item, .tou .van-field__label.radio-item {
        width: 8.625rem;
    }

    .suggest.van-cell.van-field span {
        width: 5rem;
    }
</style>
